<!-- 组件使用：
<send-time v-if="sendTimePopup" @popMsg="getPopMsg" :popMsg="getGoodTime" :title='sendTimeTitle'></send-time>

<script>
import { sendTime } from '@/components/pageComponents/sp-order/send-time';
export default {
	components: {
		sendTime
	},
	data() {
		return {
			sendTimePopup: true,
			sendTimeTitle:'',
			getGoodTime: {
				date: '',
				time: '',
				text: '请选择时间'
			}
		};
	},
	methods: {
		// 接收send-time
		getPopMsg(params) {
			this.sendTimePopup = params.show;
			this.getGoodTime.date = params.date;
			this.getGoodTime.time = params.time;
			this.getGoodTime.text = params.date ? `${params.date} ${params.time}` : '请选择时间';
			console.log('getGoodTime', this.getGoodTime);
		},
		// 打开send-time
		openSendTimePop() {
			this.sendTimePopup = true;
		}
	}
};
</script> -->
<template>
  <view class="send-time">
    <u-popup
      :show="show"
      mode="bottom"
      :round="30"
      @close="closeBg"
      @open="open"
    >
      <view class="head">
        <view></view>
        <view class="title">{{ title }}</view>
        <view class="close" @click="close" :style="{ color: themeColor }"
          >确认</view
        >
      </view>
      <view class="con">
        <view class="date-info">
          <view
            @click="selectDate(index)"
            v-for="(item, index) in dateList"
            :key="index"
            class="li"
            :class="index === dateIndex ? 'active' : ''"
            >{{ item.date }}</view
          >
        </view>
        <view class="time-info">
          <scroll-view
            scroll-y="true"
            :scroll-into-view="toview"
            style="height: 70vh"
            :scroll-with-animation="false"
          >
            <view
              :id="'t' + item"
              @click="selectTime(index)"
              v-for="(item, index) in timeList"
              :key="index"
              class="li"
              :style="{ color: index === timeIndex ? themeColor : '' }"
            >
              {{ item }}
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  props: {
    popMsg: Object,
    title: String,
    show: Boolean,
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
  },
  data() {
    return {
      // show: true,
      dateList: [],
      dateIndex: 0,
      timeList: [],
      timeIndex: 0,
      toview: "",
    };
  },
  watch: {},
  methods: {
    open() {
      Promise.all([this.getWeekFun(), this.getTimeFun()]).finally(() => {
        this.findTimeFun();
      });
    },
    //点击背景关闭
    closeBg() {
      this.$emit("update:show", false);
      let { date, time, year, month, day } = this.popMsg;
      let params = {
        show: this.show,
        date,
        time,

        year,
        month,
        day,
      };
      this.$emit("popMsg", params);
      // console.log('日期', this.popMsg.date);
      // console.log('时间', this.popMsg.time);
    },
    //点击确认关闭
    close() {
      let { date, year, month, day } = this.dateList[this.dateIndex];
      let params = {
        show: this.show,
        date,
        time: this.timeList[this.timeIndex],

        year,
        month,
        day,
      };
      this.$emit("popMsg", params);
      this.$emit("update:show", false);
      console.log("日期", this.dateList[this.dateIndex].date);
      console.log("时间", this.timeList[this.timeIndex]);
    },
    //选择日期
    selectDate(index) {
      this.dateIndex = index;
    },
    //选择时间
    selectTime(index) {
      this.timeIndex = index;
    },

    // 获取七天的星期
    getWeekFun() {
      //获取当前年月日
      let now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth() + 1; //得到月份
      var date = now.getDate(); //得到日期

      let check = [];
      for (let i = 0; i < 7; i++) {
        //24 * 3600 * 1000 就是计算一天的时间
        var date = new Date(now.getTime() + i * 24 * 3600 * 1000);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        let day = date.getDate();
        let dt2 = new Date(now.getTime() + i * 24 * 3600 * 1000);
        let weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        let weekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

        //把七天的时间和星期添加到数组中
        check.push({
          year,
          month,
          day,
          date: `${month}-${day} (${weekDay[dt2.getDay()]})`,
          weekday: weekDays[dt2.getDay()],
          week: weekDay[dt2.getDay()],
        });
      }
      this.dateList = check;
      return Promise.resolve();
    },
    //获取间隔15分钟时间
    getTimeFun() {
      let tmp = [];
      for (let i = 0; i < 1440; i += 15) {
        let m = i % 60;
        let h = parseInt(i / 60);
        h = this.formatZero(h, 2);
        m = this.formatZero(m, 2);
        tmp.push(h + ":" + m);
        this.timeList = tmp;
      }
      return Promise.resolve();
    },
    formatZero(num, len) {
      if (String(num).length > len) return num;
      return (Array(len).join(0) + num).slice(-len);
    },

    // 查找当前选中
    findTimeFun() {
      let findNowTime = this.findNowTimeFun();
      this.dateList.forEach((el, index) => {
        if (el.date === this.popMsg.date) {
          this.dateIndex = index;
        }
      });
      this.timeList.forEach((el, index) => {
        let time = this.popMsg.time ? this.popMsg.time : findNowTime;
        if (el === time) {
          this.timeIndex = index;
          // 滚动位置
          this.toview = `t${this.timeList[index]}`;
        }
      });
    },
    // 找最接近的时间
    findNowTimeFun() {
      let now = new Date();
      let getHours = now.getHours();
      let getMinutes = now.getMinutes();
      // console.log('当前分钟数', getMinutes)

      let minutArr = [0, 15, 30, 45];
      let index = 0; // 保存最接近数值在数组中的索引
      let d_value = Number.MAX_VALUE; // 保存差值绝对值，默认为最大数值
      for (let i = 0; i < minutArr.length; i++) {
        let new_d_value = Math.abs(minutArr[i] - getMinutes); // 新差值
        if (new_d_value <= d_value) {
          // 如果新差值绝对值小于等于旧差值绝对值，保存新差值绝对值和索引
          if (new_d_value === d_value && minutArr[i] < minutArr[index]) {
            // 如果数组中两个数值跟目标数值差值一样，取大
            continue;
          }
          index = i;
          d_value = new_d_value;
        }
      }
      // 补0
      let hours = String(getHours);
      if (hours.length < 2) {
        hours = `0${getHours}`;
      }
      let minut = minutArr[index];
      if (minut == 0) {
        minut = "00";
      }
      let result = `${hours}:${minut}`;
      return result; // 返回最接近的数值
    },
  },
};
</script>

<style lang="scss" scoped>
.send-time {
  .head {
    display: flex;
    justify-content: space-between;
    background-color: #f5f5f5;
    border-radius: 30rpx 30rpx 0 0;
    padding: 40rpx 0;
    box-sizing: border-box;

    view {
      flex: 1;
      text-align: center;
    }

    .title {
      flex: 2;
      font-weight: bold;
    }

    .close {
      text-align: right;
      margin-right: 36rpx;
    }
  }

  .con {
    display: flex;
    justify-content: space-between;

    .date-info {
      flex: 1;
      background-color: #f6f6f6;
      max-height: 70vh;
      overflow-y: scroll;
      text-align: center;

      .li {
        padding: 35rpx 0;
        color: #b8b8b8;
      }

      .active {
        background-color: white;
        color: #3e3e3e;
        font-weight: bold;
      }
    }

    .time-info {
      flex: 1;
      text-align: left;
      .li {
        padding: 35rpx 0;
        padding-left: 60rpx;
        box-sizing: border-box;
      }
    }
  }
}
</style>
